package models.features;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Scanner;

import views.features.CreateAccountView;
import core.User;
import core.database.DataBaseManager;

public class LoginMenu {
	static Scanner sc = new Scanner(System.in);
	private String username;
	private String password;
	private String secretQuestion;
	private String secretAnswer;
	private User currentUser;
	private boolean problemConnection = false; // variabile per notificare un problema con la connessione al database. FALSE: nessun problema.

	public LoginMenu() throws SQLException, IOException {
		try {
			DataBaseManager.connectDefaultFile();
		} catch (FileNotFoundException | SQLException e) {
			System.out.println(e + " file non trovato in LoginMenu");
			problemConnection = true; // c'è un problema. Questo dato verra utilizzato dal controller per segnalarlo all'utente tramite la view
		}
	}

	public boolean tryConnection(File f) throws SQLException {
		try{
			problemConnection = DataBaseManager.connectWithFile(f);
		}catch(Exception e){
			return false;
		}
		return problemConnection;
	}

	public boolean getStatusConnection() {
		return problemConnection;
	}

	/**
	 * Avvia il menu principale a riga di comando.
	 *  
	 * @throws SQLException
	 */
	@SuppressWarnings("all")
	public void startView() throws SQLException {
		System.out.println("BENVENUTO IN M-HEALTH");
		System.out.println("Cosa vuoi fare? \nCOMANDI:\n-accedi;\n-esci.");
		String input = sc.nextLine();
		boolean correctInput = false;
		if (input.equalsIgnoreCase("accedi")) {
			System.out.println("Hai già un account?");
			input = sc.nextLine();
			// LOGIN ACCOUNT ESISTENTE
			if (input.equalsIgnoreCase("si")) {
				do {
					System.out.println("Username: ");
					username = sc.nextLine();
					System.out.println("Password: ");
					password = sc.nextLine();
				} while (!verifyLoginInput(username, password));
				currentUser = createUserInstance(username, password);
				System.out.println("Creata istanza di " + currentUser);
			}

			// CREAZIONE NUOVO ACCOUNT
			else if (input.equalsIgnoreCase("no")) { // Si procede alla
														// creazione di un nuovo
														// account
				System.out.println("CREAZIONE DI UN NUOVO ACCOUNT");
				correctInput = false;
				do {
					System.out.println("Nuovo username: ");
					username = sc.nextLine();

				} while (!verifyUserInput(username));
				System.out.println("Nuova password: ");
				password = sc.nextLine();
				System.out.println("Domanda Segreta: ");
				secretQuestion = sc.nextLine();
				System.out.println("Risposta Segreta: ");
				secretAnswer = sc.nextLine();
				User user = new User(username, password, secretQuestion,
						secretAnswer, 0, 0);
				System.out.println(user);
				DataBaseManager.addUser(user); // inserisce una nuova tupla
												// nella tabella "utenti" del
												// database
			}
			// USCITA
			else if (input.equalsIgnoreCase("esci")) {
				System.out.println("M-HEALTH Terminato dall'utente");
				System.exit(0);
			}
		}

	}

	public User createUserInstance(String username, String password) {
		User newUser = null;
		try {
			newUser = DataBaseManager.createUser(username, password);
		} catch (SQLException | IllegalArgumentException e1) {
		}
		if (newUser == null)
			throw new IllegalStateException("Utente non trovato");
		return newUser;
	}

	public boolean createUserTuple(User user) throws SQLException {
		boolean status = DataBaseManager.addUser(user);
		if (status)
			System.out.println("AGGIUNTO NUOVO UTENTE AL DATABASE:\n" + user);
		else
			System.out.println("Utente già presente nel database");
		return status;
	}

	public String recoveryPassword(String username, String currentSecretAnswer)
			throws SQLException {
		String password = getPassword(username);
		if (currentSecretAnswer.equalsIgnoreCase(DataBaseManager
				.getSecretAnswer(username)))
			return password;
		throw new IllegalStateException("Risposta segreta errata");
	}

	public boolean verifyUserInput(String username) throws SQLException {
		return DataBaseManager.verifyUserExistence(username);
	}

	public boolean verifyLoginInput(String username, String password)
			throws SQLException {
		if (!verifyUserInput(username)) {
			System.out.println("Utente non trovato");
			return false;
		}
		if (!DataBaseManager.verifyLogin(username, password)) {
			System.out.println("Password errata");
			return false;
		}
		return true;
	}

	private String getPassword(String username) throws SQLException {
		return DataBaseManager.getCryptedPassword(username);
	}

	public String getSecretQuestion(String user) throws SQLException {
		return DataBaseManager.getSecretQuestion(user);
	}
	
	public static File createAccessFile(String userName, String psw) throws IOException{
		PrintWriter pw = new PrintWriter(new FileWriter("resources/AccessoDatabase.txt"));
		pw.println(userName);
		pw.println(psw);
		pw.close();
		return new File("resources/AccessoDatabase.txt");
	}
	
	public static void main(String [] args){
		try {
			createAccessFile("INO", "OI");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
